package com.manager.gen.module.platform.core.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.manager.commons.utils.PinyinUtil;
import com.manager.core.module.manager.entity.LayThreeData;
import com.manager.core.shiro.realm.SecurityRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.manager.commons.Constant;
import com.manager.commons.utils.StringUtil;
import com.manager.commons.base.DataGrid;
import com.manager.commons.mybatis.dao.GenericDao;
import com.manager.commons.mybatis.service.GenericService;
import com.manager.core.module.manager.dao.PlatformRoleDao;
import com.manager.core.module.manager.dao.PlatformRolePermissionDao;
import com.manager.core.module.manager.entity.PlatformRole;
import com.manager.gen.module.platform.core.entity.view.PlatformRoleView;
import com.manager.core.web.json.AjaxJson;

/**
 * PlatformRoleService
 *
 * @author H
 * @version 1.0
 */
@Service
public class PlatformRoleService extends GenericService<PlatformRole> {

    @Autowired
    private PlatformRolePermissionDao prpDao;
    @Autowired
    private PlatformRoleDao jdbcDao;
    @Autowired
    SecurityRealm securityRealm;

    @Override
    public GenericDao<PlatformRole> getDao() {
        return jdbcDao;
    }

    /**
     *
     */
    @Override
    public DataGrid queryPage(Map<String, Object> params) {
        if (null != params) {
            int count = jdbcDao.countMap(params);
            List<PlatformRole> list = jdbcDao.queryMap(params);
            return new DataGrid(count, list);
        }
        return new DataGrid(0, new ArrayList<PlatformRole>());
    }


    /**
     *
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson save(Map<String, Object> _map) {
        try {
            if (null != _map) {
                int f = 0;

                if (StringUtil.isNotEmpty(_map.get("_id") + "")) {
                    f = jdbcDao.updateMap(_map);
                } else {
                    String prCode = PinyinUtil.getFirstLetter(getParamsString(_map, "prName"));
                    _map.put("prCode", "pr_" + prCode.toLowerCase());
                    // 先添加角色表
                    f = jdbcDao.insertMap(_map);
                }
                // 先删除已有权限值
                prpDao.deleteRolePermission(_map);
                if (_map.containsKey("_ids")) {
                    prpDao.insertMap(_map);
                }
                securityRealm.updateAuthorization();
                return new AjaxJson(f);
            }
            return new AjaxJson("参数错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxJson("异常错误，请稍后再试");
    }

    /**
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson destroy(Map<String, Object> _map) {
        try {
            int f = 0;
            if (null != _map) {
                // 删除角色权限关联表
                f = prpDao.destroyMap(_map);
                if (f >= 0) {
                    // 删除用户角色表中记录
                    f = jdbcDao.destroyUserRole(_map);
                    if (f >= 0) {
                        // 删除角色主表记录
                        f = jdbcDao.destroyMap(_map);
                    }
                    return new AjaxJson(f);
                }
                return new AjaxJson("删除失败");
            }
            return new AjaxJson("参数错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxJson("异常错误，请稍后再试");
    }

    @Override
    public PlatformRole getModel() {
        return new PlatformRole();
    }

    /**
     * 查询用户角色
     *
     * @param map
     * @return
     */
    public List<PlatformRoleView> queryViews(Map<String, Object> map) {
        return jdbcDao.queryViews(map);
    }


    /**
     * 查询权限树
     *
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public List<LayThreeData> queryPermissionnaxTree(Map<String, Object> _map) {
        List<LayThreeData> lhldLists = jdbcDao.queryPermissionnaxTree(_map);
        if (lhldLists != null && !lhldLists.isEmpty()) {
            queryPermissionnaxTree(_map, lhldLists);
        }
        return lhldLists;
    }

    /**
     * 递归循环加载菜单
     *
     * @param _map
     * @param lhldLists
     */
    public void queryPermissionnaxTree(Map<String, Object> _map, List<LayThreeData> lhldLists) {
        for (LayThreeData child : lhldLists) {
            if (child.getChildCount() > 0) {
                child.setChecked(false);
                _map.put("code", child.getId());
                List<LayThreeData> childList = jdbcDao.queryPermissionnaxTree(_map);
                child.setChildren(childList);
                queryPermissionnaxTree(_map, childList);
            }
        }
    }


    /**
     * 查询角色
     *
     * @param map
     * @return
     */
    public AjaxJson queryRolesByUser(Map<String, Object> map) {
        map.put("_status", Constant.DbStatus.ENABLE.getEcode());
        List<PlatformRoleView> roles = queryViews(map);
        return new AjaxJson(1, "", new HashMap<String, Object>() {
            private static final long serialVersionUID = -4586341506635008970L;

            {
                put("roles", roles);
                put("puId", map.get("puId"));
            }
        });
    }
}